import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;

public class demo02 {
    public static String target="087654321";
    public static void main(String[] args) {
        bfs();
    }
    public static HashSet<String> set=new HashSet<>();
    public static int[] dx={-2,-1,1,2};
    public static void bfs(){
        Queue<String> queue=new LinkedList<>();
        queue.add("012345678");
        set.add("012345678");
        int ans=0;
        while (!queue.isEmpty()){
            int size=queue.size();
            for (int k = 0; k < size; k++) {
                String p=queue.poll();
                if(p.equals(target)){
                    System.out.println(ans);
                    return;
                }
                char[] cp=p.toCharArray();
                int index=0;
                for (int i = 0; i < cp.length; i++) {
                    if(cp[i]=='0'){
                        index=i;
                        break;
                    }
                }
                for (int i = 0; i < dx.length; i++) {
                    int index1=(index+dx[i]+9)%9;
                    char[] tmp=cp.clone();
                    tmp[index]=cp[index1];
                    tmp[index1]=cp[index];
                    String str1= new String(tmp);
                    if(!set.contains(str1)){
                        queue.add(str1);
                        set.add(str1);
                    }
                }
            }
            ++ans;
        }
    }
}